// pages/car/car.js
const app = getApp()
var baseurl = app.baseurl.url;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    yuming: app.yuming.url,
    carts: [{
      cid: 1008,
      title: '【必优特】营养鲜鸡蛋30枚快递装',
      image: '../../img/dan.png',
      num: '1',
      price: '198.0',
      sum: '198.0',
      // selected: true
    }],
    checkednum: 0, // 选中个数
    totalprice: '', // 总价
    checked: '',
    select_all: false, // 全选
    data: [], // 购物车结算的数据
    cart_id: [], // 商品的id
    goods_id: [], // 商品goodid
    address: '', // 默认地址
    freight: '', // 运费
    w_total: '', // 运费总和
  },
  // 减
  bindMinus: function (e) {
    this.setData({
      select_all: false,
      // totalprice: 0.00
    })
    var that = this
    var index = parseInt(e.currentTarget.dataset.index);
    var num = this.data.carts[index].number;
    let id = this.data.carts[index].id
    // console.log(id);
    // 如果只有1件了，就不允许再减了
    if (num > 1) {
      num--;
    } else {

      wx.showModal({
        title: '删除提示',
        content: '是否确定删除？',
        showCancel: true,//是否显示取消按钮
        cancelText: "否",//默认是“取消”
        cancelColor: '#333',//取消文字的颜色
        confirmText: "是",//默认是“确定”
        confirmColor: '#333',//确定文字的颜色
        success: res => {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
            wx.showToast({
              title: '删除失败',
              icon: 'none',
              duration: 2000
            })
          } else {
            //点击确定 
            // wx.showToast({
            //   title: '删除成功',
            //   icon: 'none',
            //   duration: 2000
            // })
            // 删除
            wx.request({
              url: `${baseurl}/good.ShoppingCart/cart_del`,
              method: 'POST',
              data: {
                user_id: wx.getStorageSync("user_id"),
                openid: wx.getStorageSync("openid"),
                cart_id: id,
              },
              success: (res) => {
                this.list()
                wx.showToast({
                  title: res.data.msg,
                  icon: 'none',
                  duration: 2000
                })

              }
            })
          }
        },
        fail: function (res) {
          //接口调用失败的回调函数 
          wx.showToast({
            title: '删除失败',
            icon: 'none',
            duration: 2000
          })
        },

      })


    }


    // console.log(minusStatus);
    // 购物车数据
    var carts = this.data.carts;
    carts[index].number = num;
    var goods_id = carts[index].goods_id;
    var cart_id = carts[index].id;

    // console.log(num);
    // console.log(goods_id);
    wx.request({
      url: `${baseurl}/good.ShoppingCart/cart_edit`,
      data: {
        goods_id: goods_id,
        number: num,
        user_id: wx.getStorageSync("user_id"),
        openid: wx.getStorageSync("openid"),
        cart_id: cart_id
      },
      success(res) {
        // 将数值与状态写回
        that.list()
      }
    })

  },
  // 加
  bindPlus: function (e) {

    console.log(e)
    setTimeout(() => {
      console.log('11111222222222222');
      this.setData({
        select_all: false,
        totalprice: '0.00'
      })
    }, 10);

    var that = this
    var index = parseInt(e.currentTarget.dataset.index); // 当前索引
    var carts = this.data.carts; // 购物车数据
    var num = carts[index].number; // 当前数量
    if (num < 999) {
      num++
      carts[index].number = num;
      this.setData({
        carts: carts
      });
      var goods_id = carts[index].goods_id;
      var cart_id = carts[index].id;
      // console.log(carts[index]);

      // console.log('当前数量：', carts[index].number);
      // console.log('当前id：', carts[index].id);
      // 修改购物车
      wx.request({
        url: `${baseurl}/good.ShoppingCart/cart_edit`,
        data: {
          goods_id: goods_id,
          number: num,
          user_id: wx.getStorageSync("user_id"),
          openid: wx.getStorageSync("openid"),
          cart_id: cart_id
        },
        success(res) {
          wx.request({
            url: `${baseurl}/good.ShoppingCart/cart_list`,
            data: {
              user_id: wx.getStorageSync("user_id"),
              openid: wx.getStorageSync("openid")
            },
            success: (res) => {
              // console.log(res.data.data);
              that.setData({
                carts: res.data.data
              })
            }
          })
        }
      })
      this.getTotalPrice()
    } else {
      wx.showToast({
        title: '库存不足',
        icon: 'none',
        duration: 2000
      })
    }

  },
  // 全选、反选
  checkall(e) {
    var that = this
    // console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    console.log(e.detail.value == 1);
    console.log(
      '全选',
      this.data.carts
    );

    if (e.detail.value == '1') {
      this.setData({
        select_all: true
      })
      // console.log('全选',this.data.carts.length);
      // //取反// 改变状态
      // carts[index].selected = !selected;

      let arr = []
      let cart_data = []
      let good_lis
      for (let i = 0; i < this.data.carts.length; i++) {
        //循环给每个商品的selected赋值
        that.data.carts[i].selected = (that.data.select_all)
        that.data.checkednum++
        // 结算数据
        arr.push(that.data.carts[i].id)
        good_lis = {
          weight: that.data.carts[i].weight,
          title: that.data.carts[i].title,
          thumb: that.data.carts[i].thumb,
          goods_id: that.data.carts[i].goods_id,
          price: that.data.carts[i].price,
          number: that.data.carts[i].number,
          type: 1 //(1商品2充值卡)
        }
        cart_data.push(good_lis)
      }
      // console.log('arr', arr);
      // console.log('选中产品', cart_data);
      this.setData({
        cart_id: [...this.data.cart_id, ...arr], // 结算数据
        data: [...this.data.data, ...cart_data] // 结算数据
      })
      // console.log('选中产品', this.data.data);
      console.log('选中数量', this.data.checkednum);
      this.setData({
        carts: this.data.carts,
        checkednum: this.data.checkednum
      })
      this.getTotalPrice()

    } else if (e.detail.value == '') {
      // 全不选
      // 反选
      this.setData({
        select_all: false,
        checkednum: 0
      })
      console.log('全不选',this.data.carts.length);
      for (let i = 0; i < this.data.carts.length; i++) {
        //循环给每个商品的selected赋值
        that.data.carts[i].selected = (that.data.select_all)
        // console.log(that.data.select_all);

        if (that.data.carts[i].selected == true) {
          // 全选获取选中的值 以字符串拼接的形式 拼成一个字符串
          // arr = arr + "," + that.data.carts[i].goods_id;
        }
      }
      this.setData({
        carts: this.data.carts
      })
      // console.log('全不选',this.data.carts);
      // console.log('选中数量', this.data.checkednum);
      this.getTotalPrice()
    }
  },
  // 复选框是否勾选
  checkchange(e) {
    var that = this
    // console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    // const checked = e.detail.value // 是否选中
    var index = e.currentTarget.dataset.index; // 获取当前点击事件的下标索引
    // var goods_id = carts[index].goods_id;
    let carts = this.data.carts; //获取购物车列表
    let selected = carts[index].selected; // 获取当前商品的选中状态 获取购物车里面的value值
    // 结算数据
    let arr = []
    arr.push(carts[index].id)
    let cart_data = []
    let good_lis = {
      weight: carts[index].weight,
      title: carts[index].title,
      thumb: carts[index].thumb,
      goods_id: carts[index].goods_id,
      price: carts[index].price,
      number: carts[index].number,
      type: 1 //(1商品2充值卡)
    }
    // console.log(selected);
    // 获取当前商品的选中状态 false
    if (selected == false) {
      cart_data.push(good_lis)
    }

    console.log('点中产品', cart_data);

    //取反// 改变状态  添加选中属性
    carts[index].selected = !selected;

    // console.log(this.data.cart_id);
    // console.log('点击的产品', this.data.data);
    console.log('购物车', this.data.carts);
    // 选中数量
    var checkednum = 0
    let arr_id = []  // 选中商品的id
    // 循环列表得到每个数据
    carts.forEach(function (value, index, arr) {
      // value: 每个数组元素
      // index: 索引
      // arr: 数组本身
      // console.log(carts[i].selected);
      if (value.selected == true) {
        checkednum++
        arr_id.push(value.id)
        // console.log('11', checkednum);
      }
      // console.log(checkednum);
      // console.log(carts.length);
    })
    // this.setData({
    //   checkednum
    // })
    console.log('arr_id', arr_id);
    // console.log(this.data.cart_id);
    this.setData({
      carts: carts,
      // cart_id: [...this.data.cart_id, ...arr], // 结算数据
      cart_id: [...arr_id], // 结算数据
      data: [...this.data.data, ...cart_data], // 结算数据
      checkednum
    })
    // console.log(this.data.cart_id);

    // console.log('复选框选中数量', this.data.checkednum);
    // console.log(this.data.carts);

    if (checkednum == carts.length) {
      that.setData({
        select_all: true
      })
    } else {
      that.setData({
        select_all: false
      })
    }
    this.getTotalPrice(); // 重新获取总价
  },
  // 结算
  settlement() {
    if (this.data.checkednum == 0) {
      wx.showToast({
        title: '快选择一件商品结算吧 ！',
        icon: 'none',
        duration: 2000
      })
    } else {
      let shopdata = JSON.stringify(this.data.data)
      // console.log(this.data.data);
      // console.log('11111111112', this.data.cart_id);
      wx.reLaunch({
        url: `/pages/confirm_car/confirm_car?shopdata=${shopdata}&cart_id=${this.data.cart_id}`,
      })

    }

  },

  // 删除按钮
  closebtn() {
    if (this.data.checkednum == 0) {
      wx.showToast({
        title: '暂无删除的产品 ！',
        icon: 'none',
        duration: 2000
      })
    } else {
      // console.log(this.data.cart_id);
    
      wx.request({
        url: `${baseurl}/good.ShoppingCart/cart_del`,
        method: 'POST',
        data: {
          user_id: wx.getStorageSync("user_id"),
          openid: wx.getStorageSync("openid"),
          cart_id: this.data.cart_id,
        },
        success: (res) => {
          this.list()
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          this.setData({
            select_all: false
          })
        }
      })
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let openid = wx.getStorageSync("openid")
    // 是否有openid登录
    if (openid != '') {
      // 列表
      this.list()
    } else {
      wx.reLaunch({
        url: '/pages/login/login'
      })
    }
  },
  // 列表
  list() {
    wx.request({
      url: `${baseurl}/good.ShoppingCart/cart_list`,
      method: 'POST',
      data: {
        user_id: wx.getStorageSync("user_id"),
        openid: wx.getStorageSync("openid")
      },
      success: (res) => {
        // console.log(res.data.data);
        // 添加 selected 属性，判断当前是否选中
        res.data.data.forEach((item, index) => {
          item['selected'] = false
        });
        // console.log(res.data.data);
        this.setData({
          carts: res.data.data
        })
        // 共计
        this.getTotalPrice()
      }
    })
    // 默认地址
    wx.request({
      url: `${baseurl}/user.UserAddress/get_details`,
      method: 'POST',
      data: {
        user_id: wx.getStorageSync("user_id"),
        status: 1
      },
      success: (res) => {
        // console.log(res.data.data);
        this.setData({
          address: res.data.data
        })
        // this.freight()
      }
    })
  },
  // 运费
  // freight() {
  //   wx.request({
  //     url: `${baseurl}/order.Order/Freight`,
  //     method: 'POST',
  //     data: {
  //       user_id: wx.getStorageSync("user_id"),
  //       province: this.data.address.province,
  //     },
  //     success: (res) => {
  //       // console.log(res.data);
  //       // console.log(res.data.data);
  //       this.setData({
  //         freight: res.data.data
  //       })
  //     }
  //   })
  // },
  // 总价
  getTotalPrice() {
    var that = this
    // 获取商品列表数据
    let carts = this.data.carts;
    // console.log(carts);
    // 声明一个变量接收数组列表price
    let total = 0;
    let w_total = 0 // 运费
    // 循环列表得到每个数据
    for (let i = 0; i < carts.length; i++) {
      // console.log(carts[i].selected);
      // 判断选中计算价格
      if (carts[i].selected == true) {
        // 所有价格加起来 count_money
        let a = carts[i].number * carts[i].price
        let f = carts[i].weight * this.data.freight // 运费
        // console.log(carts[i].weight);
        // console.log(that.data.freight);
        // console.log(f);
        total += parseFloat(a) + parseFloat(f);
        w_total += f
      }
    }
    // 最后赋值到data中渲染到页面
    this.setData({
      carts: carts,
      totalprice: total.toFixed(2),
      w_total: w_total.toFixed(2)
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.list()
    this.setData({
      select_all: false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})